770C - Online Courses In BSU - CodeForces Solution


*special problem dfs and similar graphs implementation *1500

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define endl '\n'
const ll mx = 1e5;
const int MOD = 1000000007;
const double eps = 1e-6;
bool loop = false;
int visited[mx+1];
vector<int> ans;

void dfs(vector<vector<int>> &adj,int node){
    if(visited[node]==0){
        visited[node]=1;
        for(auto child:adj[node])dfs(adj,child);
        visited[node]=2;
        ans.push_back(node);
    }else if(visited[node]==1){
        loop = true;
        return;
    }
}

int main()
{
    ios_base::sync_with_stdio(false); cin.tie(nullptr);

    //freopen ("input.txt","r",stdin);
    //freopen ("output.txt","w",stdout);

    int n,k;cin>>n>>k;
    vector<int> mainCourses(k);
    for(auto &course:mainCourses)cin>>course;
    vector<vector<int>> adj(n+1);
    for(int i=1;i<=n;i++){
        int num;cin>>num;
        while(num--){
            int temp;cin>>temp;
            adj[i].push_back(temp);
        }
    }

    for(auto course:mainCourses){
        dfs(adj,course);
    }
    if(loop){
        cout<<-1<<endl;
        return 0;
    }
    cout<<ans.size()<<endl;
    for(auto course:ans)cout<<course<<" ";
    cout<<endl;

    return 0;
}
	 	  	  		 	   	 	 	 		  	 	 		


Comments

Submit
0 Comments
More Questions

766A - Mahmoud and Longest Uncommon Subsequence
701B - Cells Not Under Attack
702A - Maximum Increase
1656D - K-good
1426A - Floor Number
876A - Trip For Meal
1326B - Maximums
1635C - Differential Sorting
961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament